package com.starinside.wp.service.impl;



import com.starinside.wp.domain.ChildActivity;
import com.starinside.wp.domain.Classes;
import com.starinside.wp.domain.UserActiveRegistration;
import com.starinside.wp.foundation.vo.ChildActivityVo;
import com.starinside.wp.repository.*;
import com.starinside.wp.service.ChildActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * (ChildActivity)表服务实现类
 *
 * @author makejava
 * @since 2025-02-21 15:04:17
 */
@Service("childActivityService")
public class ChildActivityServiceImpl implements ChildActivityService {
    @Autowired
    ChildActivityRepository childActivityRepository;
    @Autowired
    RelClassesChildrenRepository relClassesChildrenRepository;
    @Autowired
    ClassesRepository classesRepository;
    @Autowired
    UserActiveRegistrationRepository userActiveRegistrationRepository;

    @Override
//    public List<ChildActivityVo> activeList(String childId) {
//        // 获取班级 ID 列表
//        List<String> classesIdsByChildrenId = relClassesChildrenRepository.findClassesIdsByChildrenId(childId);
//        System.out.println("DEBUG - 关联班级 IDs: " + classesIdsByChildrenId); // 确保非空且值正确
//
//        Specification<ChildActivity> specification = ChildActivitySpecification.buildSpecification(null, classesIdsByChildrenId);
//
////        // 打印生成的 SQL 条件（需开启 Hibernate SQL 日志）
////        List<ChildActivity> activities = childActivityRepository.findAll(specification);
////        System.out.println("DEBUG - 实际查询结果数量: " + activities.size());
//
//        List<Object[]> results = childActivityRepository.findAll(specification).stream()
//                .map(activity -> new Object[]{
//                        activity.getTitle(),
//                        activity.getClassIds(),
//                        activity.getType(),
//                        activity.getAddress(),
//                        activity.getStartTime(),
//                        activity.getEndTime(),
//                        activity.getDeadlineTime(),
//                        activity.getContent(),
//                        activity.getRemark(),
//                        activity.getAreaId(),
//                        activity.getSourceType(),
//                        activity.getCreateTime(),
//                        activity.getId()
//                })
//                .collect(Collectors.toList());
//        System.out.println("Test Results Size: " + results.size());
//
//
//        // 转换为VO对象，并填充classNames
//        List<ChildActivityVo> list = results.stream()
//                .map(result -> {
//                    ChildActivityVo vo = new ChildActivityVo();
//                    vo.setTitle((String) result[0]);
//                    vo.setClassIds((String) result[1]);
//                    vo.setType((String) result[2]);
//                    vo.setAddress((String) result[3]);
//                    vo.setStartTime(result[4] != null ? (Date) result[4] : null);
//                    vo.setEndTime(result[5] != null ? (Date) result[5] : null);
//                    vo.setDeadlineTime(result[6] != null ? (Date) result[6] : null);
//                    vo.setContent((String) result[7]);
//                    vo.setRemark((String) result[8]);
//                    vo.setAreaId((String) result[9]);
//                    vo.setSourceType(result[10] != null ? ((Number) result[10]).intValue() : null);
//                    vo.setCreateTime(result[11] != null ? (Date) result[11] : null);
//                    vo.setId((String) result[12]);
//                    UserActiveRegistration byActivityIdAndChildrenId = userActiveRegistrationRepository.findByActivityIdAndChildrenId((String) result[12], childId);
//                    if (byActivityIdAndChildrenId != null) {
//                        if (byActivityIdAndChildrenId.getIsActive()) {
//                            vo.setStatus(1);
//                        } else if (vo.getDeadlineTime().before(new Date())) {
//                            vo.setStatus(2);
//                        } else if (vo.getEndTime().before(new Date())) {
//                            vo.setStatus(3);
//                        } else {
//                            vo.setStatus(0);
//                        }
//                    } else {
//                        vo.setStatus(0);
//                    }
//
//                    // 根据classIds获取classNames
//                    if (vo.getClassIds() != null && !vo.getClassIds().isEmpty()) {
//                        List<String> classNames = Arrays.stream(vo.getClassIds().split(","))
//                                .map(String::trim)
//                                .filter(classId -> !classId.isEmpty())
//                                .map(classId -> classesRepository.findById(classId).orElse(null))
//                                .filter(Objects::nonNull)
//                                .map(Classes::getName)
//                                .collect(Collectors.toList());
//                        vo.setClassNames(String.join(", ", classNames));
//                    }
//
//                    Long size = userActiveRegistrationRepository.findCountByAreaIdAndActivityId1(vo.getId());
//                    vo.setActiveSize(size);
//                    return vo;
//                })
//                .collect(Collectors.toList());
//
//        return list;
//    }
    public List<ChildActivityVo> activeList(String childId) {
        // 获取关联班级ID列表
        List<String> classesIdsByChildrenId = relClassesChildrenRepository.findClassesIdsByChildrenId(childId);
        Specification<ChildActivity> specification = ChildActivitySpecification.buildSpecification(null, classesIdsByChildrenId);

        // 查询ChildActivity列表
        List<ChildActivity> activities = childActivityRepository.findAll(specification);

        // 收集所有activityIds和classIds
        List<String> activityIds = activities.stream().map(ChildActivity::getId).collect(Collectors.toList());
        List<String> allClassIds = activities.stream()
                .map(ChildActivity::getClassIds)
                .filter(Objects::nonNull)
                .flatMap(classIds -> Arrays.stream(classIds.split(",")))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .distinct()
                .collect(Collectors.toList());

        // 批量查询班级名称
        Map<String, String> classIdToNameMap = classesRepository.findAllById(allClassIds)
                .stream()
                .collect(Collectors.toMap(Classes::getId, Classes::getName));

        // 批量查询用户注册信息
        Map<String, UserActiveRegistration> registrationMap = userActiveRegistrationRepository
                .findByActivityIdInAndChildrenId(activityIds, childId)
                .stream()
                .collect(Collectors.toMap(UserActiveRegistration::getActivityId, Function.identity()));

        // 批量统计活动参与人数
        Map<String, Long> countMap = userActiveRegistrationRepository.countByActivityIds(activityIds)
                .stream()
                .collect(Collectors.toMap(
                        obj -> (String) obj[0],
                        obj -> (Long) obj[1]
                ));

        // 转换为VO
        List<ChildActivityVo> list = activities.stream().map(activity -> {
            ChildActivityVo vo = new ChildActivityVo();
            // 设置基本属性
            vo.setTitle(activity.getTitle());
            vo.setClassIds(activity.getClassIds());
            vo.setType(activity.getType());
            vo.setAddress(activity.getAddress());
            vo.setStartTime(activity.getStartTime());
            vo.setEndTime(activity.getEndTime());
            vo.setDeadlineTime(activity.getDeadlineTime());
            vo.setContent(activity.getContent());
            vo.setRemark(activity.getRemark());
            vo.setAreaId(activity.getAreaId());
            vo.setSourceType(activity.getSourceType());
            vo.setCreateTime(activity.getCreateTime());
            vo.setId(activity.getId());

            // ... 其他属性设置

            // 处理班级名称
            if (activity.getClassIds() != null) {
                List<String> classNames = Arrays.stream(activity.getClassIds().split(","))
                        .map(String::trim)
                        .filter(s -> !s.isEmpty())
                        .map(classIdToNameMap::get)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                vo.setClassNames(String.join(", ", classNames));
            }

            // 处理状态
            UserActiveRegistration registration = registrationMap.get(activity.getId());
             // 优先判断活动时间状态 activity.getEndTime().before(new Date())
            if (activity.getEndTime().before(new Date())) {
                vo.setStatus(3); // 已结束（覆盖所有用户）
            } else if (activity.getDeadlineTime().before(new Date())) {
                vo.setStatus(2); // 已截止（覆盖所有用户）
            } else {
                // 再判断用户报名状态
                if (registration != null) {
                    vo.setStatus(registration.getIsActive() ? 1 : 0); // 已报名或未激活
                } else {
                    vo.setStatus(0); // 未报名且活动未截止
                }
            }

            // 设置参与人数
            vo.setActiveSize(countMap.getOrDefault(activity.getId(), 0L));

            return vo;
        }).collect(Collectors.toList());

        return list;
    }


    @Override
    public ChildActivityVo getDetailByActiveId(String activeId, String childId) {
        ChildActivity activity = childActivityRepository.findById(activeId).get();
        ChildActivityVo vo = new ChildActivityVo();
        // 设置基本属性
        vo.setTitle(activity.getTitle());
        vo.setClassIds(activity.getClassIds());
        vo.setType(activity.getType());
        vo.setAddress(activity.getAddress());
        vo.setStartTime(activity.getStartTime());
        vo.setEndTime(activity.getEndTime());
        vo.setDeadlineTime(activity.getDeadlineTime());
        vo.setContent(activity.getContent());
        vo.setRemark(activity.getRemark());
        vo.setAreaId(activity.getAreaId());
        vo.setSourceType(activity.getSourceType());
        vo.setCreateTime(activity.getCreateTime());
        vo.setId(activity.getId());

        Long size = userActiveRegistrationRepository.findCountByAreaIdAndActivityId1(activity.getId());
        vo.setActiveSize(size);
        UserActiveRegistration registration = userActiveRegistrationRepository.findByActivityIdAndChildrenId(activity.getId(), childId);
        if (registration != null) {
            if (registration.getIsActive()) {
                vo.setStatus(1);
            } else if (activity.getDeadlineTime().before(new Date())) {
                vo.setStatus(2);
            } else if (activity.getEndTime().before(new Date())) {
                vo.setStatus(3);
            } else {
                vo.setStatus(0);
            }
        } else {
            vo.setStatus(0);
        }
        return vo;
    }


}
